//
//  QWForgetController.m
//  qwm
//
//  Created by kevin on 2023/3/26.
//

#import "QWForgetController.h"
#import "QWRegCell.h"
#import "QWLoginButtonCell.h"
#import "QWForCodeCell.h"
#import "QWRegPassTipsView.h"

@interface QWForgetController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *menusArr;

@end

@implementation QWForgetController
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (AppProfile.timeModel.timeSecond>0 &&AppProfile.timeModel.timer) {
        [self loadtTimer];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"重制密码";
    
    [self loadInfo];
    [self tableView];
}

- (void)loadInfo{
    self.menusArr = @[
        @{
            @"name":@"手机号",
            @"textFieldPal":@"请输入手机号",
        },
        @{
            @"name":@"密码",
            @"textFieldPal":@"请输入密码",
        },
        @{
            @"name":@"确认密码",
            @"textFieldPal":@"请再次输入密码",
        },
        @{
            @"name":@"验证码",
            @"textFieldPal":@"请输入验证码",
        },
    ];
}

- (UITableView *)tableView{
    if(!_tableView){
        _tableView =[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 400;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedSectionFooterHeight=0;
        _tableView.estimatedSectionHeaderHeight=0;
        _tableView.showsVerticalScrollIndicator=NO;
        _tableView.showsHorizontalScrollIndicator=NO;
        
        _tableView.delegate =self;
        _tableView.dataSource =self;
        
        [_tableView registerNib:[UINib nibWithNibName:@"QWRegCell" bundle:nil] forCellReuseIdentifier:@"QWRegCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"QWForCodeCell" bundle:nil] forCellReuseIdentifier:@"QWForCodeCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"QWLoginButtonCell" bundle:nil] forCellReuseIdentifier:@"QWLoginButtonCell"];
        
        _tableView.backgroundColor=Color_TableView_Gray;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;

        
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        
    }
    return _tableView;
}

#pragma mark- UITableViewDelegate,UITableViewDataSource
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return section==0 ? 20.0 : 0.0000001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return section==0 ? 50 : 0.0000001;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return section==0 ? self.menusArr.count: 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        if(indexPath.row == self.menusArr.count-1){
            QWForCodeCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QWForCodeCell"];
            cell.textField.tag = 2000+indexPath.row+1;
            cell.codeBtnClickBlock = ^{
                [self reqCode];
            };
            return cell;
        }else{
            QWRegCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QWRegCell"];
            cell.textField.keyboardType = UIKeyboardTypeDefault;
            if(indexPath.row == 0){
                cell.textField.text = self.phone;
                cell.textField.keyboardType = UIKeyboardTypeNumberPad;
            }
            cell.textField.tag = 2000+indexPath.row+1;
            NSDictionary *dic =self.menusArr[indexPath.row];
            cell.nameLabel.text = dic[@"name"];
            cell.textField.placeholder = dic[@"textFieldPal"];
            cell.textField.secureTextEntry = [dic[@"name"] isEqualToString:@"密码"] || [dic[@"name"] isEqualToString:@"确认密码"];
            return cell;
        }
    }else{
        QWLoginButtonCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QWLoginButtonCell"];
        [cell.loginButton setTitle:@"确定" forState:UIControlStateNormal];
        cell.loginClickBlock = ^{
            [self confirmResetPassword];
        };
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.view endEditing:YES];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if(section == 0){
        QWRegPassTipsView *view = [[QWRegPassTipsView alloc]init];
        return view;
    }else{
        return  [UIView new];
    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    if (!(scrollView.isTracking || scrollView.isDecelerating)) {
//            //不是用户滚动的，比如setContentOffset等方法，引起的滚动不需要处理。
//        return;
//    }
//
//    [self.view endEditing:YES];
}

#pragma mark - 修改密码-请求
- (void)confirmResetPassword{
    UITextField *phoneField =(UITextField *)[_tableView viewWithTag:2000+1];
    UITextField *passwordField =(UITextField *)[_tableView viewWithTag:2000+2];
    UITextField *password2Field =(UITextField *)[_tableView viewWithTag:2000+3];
    UITextField *codeField =(UITextField *)[_tableView viewWithTag:2000+4];

    NSString * phone = phoneField.text;
    NSString * pwd1 = [NSString stringWithFormat:@"%@",passwordField.text];
    NSString * pwd2 = [NSString stringWithFormat:@"%@",password2Field.text];
    NSString * code = codeField.text;

    if (phone.length != 11) {
        [SWHUDUtil hideHudViewWithMessageSuperView:self.view withMessage:@"手机号不能为空"];
        return;
    }
    
    if (IsStringEmpty(pwd1)) {
        [SWHUDUtil hideHudViewWithMessageSuperView:self.view withMessage:@"密码不能为空"];
        return;
    }
    if (IsStringEmpty(pwd2)) {
        [SWHUDUtil hideHudViewWithMessageSuperView:self.view withMessage:@"确认密码不能为空"];
        return;
    }
    if (pwd1.length < 6 || pwd2.length < 6) {
        [SWHUDUtil hideHudViewWithMessageSuperView:self.view withMessage:@"请输入至少6位数密码"];
        return;
    }
    if (![pwd1 isEqualToString: pwd2]) {
        [SWHUDUtil hideHudViewWithMessageSuperView:self.view withMessage:@"两次输入的密码不一致，请重新输入"];
        return;
    }
    
    if (IsStringEmpty(code)) {
        [SWHUDUtil hideHudViewWithMessageSuperView:self.view withMessage:@"请输入验证码"];
        return;
    }
    

    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:phone forKey:@"phoneNumber"];
    [dic setValue:code forKey:@"text2"];
    [dic setValue:pwd1 forKey:@"password"];
    
    [SWHUDUtil showHudViewInSuperView:self.view withMessage:@"请等待"];
    HXPostRequest * request = [[HXPostRequest alloc] initWithRequestUrl:URL_RESET_PWD argument:dic];
    [request startWithCompletionBlockWithSuccess:^(__kindof HXRequest * _Nonnull request, NSDictionary * _Nonnull result, BOOL success) {
        NSString *data = result[@"message"];
        if ([data isEqualToString:@"ok"]) {
            [SWHUDUtil hideHudView];
            if(self.forgetSuccessBlock) self.forgetSuccessBlock(phone, pwd1);
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [SWHUDUtil hideHudViewWithFailureMessage:URL_Error];
        }
        } failure:^(__kindof HXRequest * _Nonnull request, NSString * _Nonnull errorInfo) {
            [SWHUDUtil hideHudView];
    }];

}

#pragma mark - 获取验证码-请求
- (void)reqCode{
    UITextField *phoneField =(UITextField *)[_tableView viewWithTag:2000+1];
    NSString * phone = phoneField.text;

    if (phone.length != 11) {
        [SWHUDUtil hideHudViewWithMessageSuperView:self.view withMessage:@"请输入有效的手机号"];
        return;
    }
    
    NSDictionary *dic =@{@"phone":phone};
    [SWHUDUtil showHudViewInSuperView:self.view withMessage:@"请等待"];
    __weak __typeof(self) weakSelf = self;
    HXPostRequest * request = [[HXPostRequest alloc] initWithRequestUrl:URL_SEND_OTP argument:dic];
    [request startWithCompletionBlockWithSuccess:^(__kindof HXRequest * _Nonnull request, NSDictionary * _Nonnull result, BOOL success) {
        if( [result[@"message"] isEqualToString:@"success"]){
            [SWHUDUtil hideHudView];
            [self loadtTimer];
        }else{
            [SWHUDUtil hideHudViewWithFailureMessage:@"验证码错误，请重新获取验证码。"];
        }
    } failure:^(__kindof HXRequest * _Nonnull request, NSString * _Nonnull errorInfo) {
        [SWHUDUtil hideHudView];
        AppProfile.timeModel.timeSecond=0;
        [AppProfile.timeModel.timer invalidate];
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.tableView reloadData];
    }];

}
#pragma mark-计时器
-(void)loadtTimer
{
    if (AppProfile.timeModel.timeSecond<=0) {
        AppProfile.timeModel.timeSecond=60;//验证码时间-60秒
    }
    
    [AppProfile.timeModel.timer invalidate];
    AppProfile.timeModel.timer=nil;
    AppProfile.timeModel.timer=[NSTimer scheduledTimerWithTimeInterval:1
                                                               target:self
                                                             selector:@selector(updateTime)
                                                             userInfo:nil
                                                              repeats:YES];
    
    
    [AppProfile.timeModel.timer fire];
}
-(void)updateTime
{
    UIButton *bt =(UIButton *)[_tableView viewWithTag:102];
    UILabel *label =(UILabel *)[_tableView viewWithTag:101];
    //    [bt setTitle:@"" forState:UIControlStateNormal];
    
    AppProfile.timeModel.timeSecond--;
    if (AppProfile.timeModel.timeSecond<1) {
//        [bt setTitle:@"获取" forState:UIControlStateNormal];
        label.text=@"获取";
        bt.userInteractionEnabled =YES;
        [AppProfile.timeModel.timer invalidate];
        AppProfile.timeModel.timer=nil;
        AppProfile.timeModel.timeSecond=0;
    }else
    {
        bt.userInteractionEnabled =NO;
//        [bt setTitle:[NSString stringWithFormat:@"%lds",(long)AppProfile.timeModel.timeSecond] forState:UIControlStateNormal];
        label.text =[NSString stringWithFormat:@"%lds",(long)AppProfile.timeModel.timeSecond];
    }
//    NSLog(@"时间走动==%ld",AppProfile.timeModel.timeSecond);
}

@end
